package com.qf.netty.handler;

import com.qf.netty.entity.Message;
import com.qf.netty.entity.Rooms;
import com.qf.netty.entity.User;
import com.qf.netty.handler.base.BaseMsgChannelHandler;
import com.qf.netty.utils.RoomUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.kurento.client.WebRtcEndpoint;
import org.springframework.stereotype.Component;

/**
 * 观看者退出房间的处理器
 * author Ken
 * create_time 2023/1/5
 */
@Component
@ChannelHandler.Sharable
public class SlaveOutMsgChannelHandler extends BaseMsgChannelHandler {
    @Override
    protected int action() {
        return 8;
    }

    @Override
    protected void handler(ChannelHandlerContext ctx, Message msg) {
        //获取房间号
        Integer roomId = Integer.parseInt(msg.getMsg() + "");
        //找到房间对象
        Rooms rooms = RoomUtils.getRooms(roomId);

        if (rooms == null) return;

        //获取当前的观看者对象
        for (User slave : rooms.getSlaves()) {
            if (slave.getChannel() == ctx.channel()) {
                //找到当前用户
                //将KMS资源回收
                WebRtcEndpoint webRtcEndpoint = slave.getWebRtcEndpoint();
                webRtcEndpoint.release();

                //将当前用户从观看者列表中踢出
                rooms.getSlaves().remove(slave);

                //通知其他用户，更新人数
                //通知房间中的所有用户，更新当前的观看者人数
                Message message = new Message()
                        .setAction(2)
                        .setMsg(rooms.getSlaves().size());
                //将当前消息发送给房间中的所有用户
                rooms.sendMessageAll(message, true);
                break;
            }
        }
    }
}
